package com.newshub.ai.core.client.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.newshub.ai.core.client.LLMClient;
import com.newshub.ai.model.dto.ChatRequest;
import com.newshub.ai.model.dto.ChatResponse;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * DeepSeek LLM客户端实现
 */
@Slf4j
@Component("deepseekClient")
public class DeepSeekClient implements LLMClient {

    // 硬编码配置，用于测试
    private static final String API_KEY = "sk-1a7ab5e29353472090f98e309ce81919";
    private static final String ENDPOINT = "https://api.deepseek.com/v1/chat/completions";
    private static final String MODEL_VERSION = "deepseek-chat";

    @Autowired
    @Qualifier("aiRestTemplate")
    private RestTemplate restTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public String getClientType() {
        return "DeepSeek";
    }

    @Override
    public String getModelInfo() {
        return MODEL_VERSION;
    }

    @Override
    public boolean isAvailable() {
        return true; // 硬编码返回true，用于测试
    }

    @Override
    public ChatResponse chat(ChatRequest request) {
        try {
            log.info("DeepSeek聊天请求: {}", request.getMessage());

            // 构建请求体
            Map<String, Object> requestBody = buildRequestBody(request);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + API_KEY);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                ENDPOINT,
                HttpMethod.POST,
                entity,
                Map.class
            );

            // 解析响应
            return parseResponse(response.getBody());

        } catch (Exception e) {
            log.error("DeepSeek聊天请求失败", e);
            return ChatResponse.error("DeepSeek请求失败: " + e.getMessage());
        }
    }

    /**
     * 构建请求体
     */
    private Map<String, Object> buildRequestBody(ChatRequest request) {
        Map<String, Object> requestBody = new java.util.HashMap<>();
        
        // 设置模型
        requestBody.put("model", MODEL_VERSION);
        
        // 设置消息
        List<Map<String, String>> messages = new ArrayList<>();
        
        // 添加系统消息
        if (request.getSystemPrompt() != null && !request.getSystemPrompt().isEmpty()) {
            Map<String, String> systemMessage = new java.util.HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", request.getSystemPrompt());
            messages.add(systemMessage);
        }
        
        // 添加历史消息
        if (request.getHistory() != null) {
            for (ChatRequest.ChatMessage historyMsg : request.getHistory()) {
                Map<String, String> message = new java.util.HashMap<>();
                message.put("role", historyMsg.getRole());
                message.put("content", historyMsg.getContent());
                messages.add(message);
            }
        }
        
        // 添加当前用户消息
        Map<String, String> userMessage = new java.util.HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", request.getMessage());
        messages.add(userMessage);
        
        requestBody.put("messages", messages);
        
        // 设置参数
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 4000);
        requestBody.put("stream", false); // 普通聊天不流式
        
        return requestBody;
    }

    /**
     * 解析响应
     */
    private ChatResponse parseResponse(Map<String, Object> responseBody) {
        try {
            if (responseBody == null) {
                return ChatResponse.error("DeepSeek响应为空");
            }

            // 检查错误
            if (responseBody.containsKey("error")) {
                Map<String, Object> error = (Map<String, Object>) responseBody.get("error");
                String errorMessage = (String) error.get("message");
                return ChatResponse.error("DeepSeek错误: " + errorMessage);
            }

            // 解析选择
            List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
            if (choices == null || choices.isEmpty()) {
                return ChatResponse.error("DeepSeek响应格式错误：没有选择");
            }

            Map<String, Object> choice = choices.get(0);
            Map<String, Object> message = (Map<String, Object>) choice.get("message");
            
            if (message == null) {
                return ChatResponse.error("DeepSeek响应格式错误：没有消息");
            }

            String content = (String) message.get("content");
            String finishReason = (String) choice.get("finish_reason");

            // 解析使用情况
            Map<String, Object> usage = (Map<String, Object>) responseBody.get("usage");
            Long promptTokens = usage != null ? ((Number) usage.get("prompt_tokens")).longValue() : null;
            Long completionTokens = usage != null ? ((Number) usage.get("completion_tokens")).longValue() : null;
            Long totalTokens = usage != null ? ((Number) usage.get("total_tokens")).longValue() : null;

            // 构建响应
            ChatResponse response = new ChatResponse();
            response.setSuccess(true);
            response.setContent(content);
            response.setModel(getModelInfo());
            response.setFinishReason(finishReason);
            
            // 设置token使用情况
            if (totalTokens != null) {
                ChatResponse.TokenUsage tokenUsage = new ChatResponse.TokenUsage();
                tokenUsage.setPromptTokens(promptTokens);
                tokenUsage.setCompletionTokens(completionTokens);
                tokenUsage.setTotalTokens(totalTokens);
                response.setTokenUsage(tokenUsage);
            }

            log.info("DeepSeek响应成功，内容长度: {}", content != null ? content.length() : 0);
            return response;

        } catch (Exception e) {
            log.error("解析DeepSeek响应失败", e);
            return ChatResponse.error("解析DeepSeek响应失败: " + e.getMessage());
        }
    }

    @Override
    public ChatResponse chatWithContext(ChatRequest request, List<ChatRequest.ChatMessage> context) {
        try {
            // 将上下文消息添加到请求历史中
            if (context != null && !context.isEmpty()) {
                request.setHistory(context);
            }
            
            return chat(request);
        } catch (Exception e) {
            log.error("DeepSeek带上下文聊天失败", e);
            return ChatResponse.error("DeepSeek带上下文聊天失败: " + e.getMessage());
        }
    }

    @Override
    public void chatStream(ChatRequest request, java.util.function.Consumer<String> onDelta) {
        try {
            log.info("DeepSeek流式聊天请求: {}", request.getMessage());

            // 构建流式请求体
            Map<String, Object> requestBody = buildStreamRequestBody(request);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + API_KEY);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            // 使用 RestTemplate 的流式处理
            restTemplate.execute(
                ENDPOINT,
                HttpMethod.POST,
                req -> {
                    req.getHeaders().putAll(headers);
                    req.getBody().write(objectMapper.writeValueAsBytes(requestBody));
                },
                response -> {
                    try (var reader = new java.io.BufferedReader(
                            new java.io.InputStreamReader(response.getBody()))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            if (line.startsWith("data: ")) {
                                String data = line.substring(6);
                                if ("[DONE]".equals(data)) {
                                    break;
                                }
                                try {
                                    Map<String, Object> chunk = objectMapper.readValue(data, Map.class);
                                    List<Map<String, Object>> choices = (List<Map<String, Object>>) chunk.get("choices");
                                    if (choices != null && !choices.isEmpty()) {
                                        Map<String, Object> choice = choices.get(0);
                                        Map<String, Object> delta = (Map<String, Object>) choice.get("delta");
                                        if (delta != null && delta.containsKey("content")) {
                                            String content = (String) delta.get("content");
                                            if (content != null && !content.isEmpty()) {
                                                onDelta.accept(content);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.warn("解析流式响应chunk失败: {}", data, e);
                                }
                            }
                        }
                    }
                    return null;
                }
            );

        } catch (Exception e) {
            log.error("DeepSeek流式聊天失败", e);
            onDelta.accept("流式聊天失败: " + e.getMessage());
        }
    }

    /**
     * 构建流式请求体
     */
    private Map<String, Object> buildStreamRequestBody(ChatRequest request) {
        Map<String, Object> requestBody = new java.util.HashMap<>();
        
        // 设置模型
        requestBody.put("model", MODEL_VERSION);
        
        // 设置消息
        List<Map<String, String>> messages = new ArrayList<>();
        
        // 添加系统消息
        if (request.getSystemPrompt() != null && !request.getSystemPrompt().isEmpty()) {
            Map<String, String> systemMessage = new java.util.HashMap<>();
            systemMessage.put("role", "system");
            systemMessage.put("content", request.getSystemPrompt());
            messages.add(systemMessage);
        }
        
        // 添加历史消息
        if (request.getHistory() != null) {
            for (ChatRequest.ChatMessage historyMsg : request.getHistory()) {
                Map<String, String> message = new java.util.HashMap<>();
                message.put("role", historyMsg.getRole());
                message.put("content", historyMsg.getContent());
                messages.add(message);
            }
        }
        
        // 添加当前用户消息
        Map<String, String> userMessage = new java.util.HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", request.getMessage());
        messages.add(userMessage);
        
        requestBody.put("messages", messages);
        
        // 设置流式参数
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 4000);
        requestBody.put("stream", true); // 启用流式响应
        
        return requestBody;
    }
}
